package cn.itsource.ymjs.service.impl;

import cn.itsource.ymjs.client.CourseDocClient;
import cn.itsource.ymjs.doc.CourseDoc;
import cn.itsource.ymjs.entity.CourseDetail;
import cn.itsource.ymjs.entity.CourseType;
import cn.itsource.ymjs.entity.FitnessCourse;
import cn.itsource.ymjs.query.CourseQuery;
import cn.itsource.ymjs.repository.CourseDetailRepository;
import cn.itsource.ymjs.repository.FitnessCourseRepository;
import cn.itsource.ymjs.result.JSONResult;
import cn.itsource.ymjs.service.ICourseDetailService;
import cn.itsource.ymjs.service.IFitnessCourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author 11695
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class FitnessCourseServiceImpl extends BaseServiceImpl<FitnessCourse, CourseQuery> implements IFitnessCourseService {

    @Autowired
    private FitnessCourseRepository fitnessCourseRepository;
    @Autowired
    private CourseDetailRepository courseDetailRepository;

    @Autowired
    private ICourseDetailService courseDetailService;

    @Autowired
    private CourseDocClient courseDocClient;

    /**======================================================================================
     * 方法描述：查询方法在父类，这个构造自己的查询条件
     ======================================================================================*/
    @Override
    protected Specification createWhereForSelectPage(CourseQuery courseQuery) {
        return new Specification<FitnessCourse>(){
            @Override
            public Predicate toPredicate(Root<FitnessCourse> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                if(courseQuery.getKeyword() != null){
                    //关键字模糊查询
                    Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%"+courseQuery.getKeyword()+"%");
                    query.where(criteriaBuilder.and(p1));
                }
                return query.getRestriction();
            }
        };
    }

    @Override
    public List<FitnessCourse> getAllCourse() {
        return fitnessCourseRepository.findAll();
    }

    @Override
    public void save(FitnessCourse fitnessCourse) {
        // 先添加课程获取到id再添加详情
        fitnessCourseRepository.save(fitnessCourse);
//        courseDetailService.save(fitnessCourse);
    }

    @Override
    public JSONResult online(List<Long> ids) {
        List<FitnessCourse> one = statusUpdate(ids, 1);
        List<CourseDoc> courseDocs = new ArrayList<>();
        for (Long id : ids) {
            CourseDoc courseDoc = new CourseDoc();
            //处理course里面值
            FitnessCourse course = fitnessCourseRepository.getOne(id);
            BeanUtils.copyProperties(course,courseDoc);
            //处理课程类型
            courseDoc.setCourseTypeName(course.getCourseType().getName());
            //处理影响信息
            courseDocs.add(courseDoc);
        }
        JSONResult jsonResult = courseDocClient.batchAdd(courseDocs);
        if (jsonResult.isSuccess()) {
            fitnessCourseRepository.saveAll(one);
            return jsonResult;
        } else {
            return JSONResult.error().setMessage(jsonResult.getMessage());
        }
    }

    /**
     * 修改上下架状态
     * @param ids id
     * @param i 状态
     * @return
     */
    private  List<FitnessCourse> statusUpdate(List<Long> ids, int i) {

        List<FitnessCourse> list = new ArrayList<>();
        ids.forEach(id -> {
            if (fitnessCourseRepository.existsById(id)) {
                FitnessCourse one = fitnessCourseRepository.getOne(id);
                one.setStatus(i);
                list.add(one);
            }
        });
        return list;
    }

    @Override
    public JSONResult offline(List<Long> ids) {
        List<FitnessCourse> one = statusUpdate(ids, 0);
        fitnessCourseRepository.saveAll(one);
        return  JSONResult.success();
    }
}
